<template>
  <div id="add-shuziren-video">
    <!-- 添加视频 -->
    <div class="add-form">
      <el-form :model="form" label-width="120px" ref="form" :rules="rules">
        <el-form-item label="视频名称：" prop="videoName">
          <el-input v-model="form.videoName" />
        </el-form-item>
        <el-form-item label="涉及知识点：" class="knowledge-tree-item">
          <div class="knowledge-tree" v-if="treeData && treeData.length > 0">
            <el-tree
              ref="knowledgeTree"
              :data="treeData"
              :props="defaultProps"
              node-key="id"
              default-expand-all
              class="chapter-tree"
            >
              <template #default="{ data }">
                <span class="custom-tree-node">
                  <!-- 只有子节点（有value值）才显示radio -->
                  <el-radio
                    v-if="data.value"
                    v-model="selectedKnowledgeValue"
                    :label="data.value"
                    @change="handleKnowledgeSelect(data)"
                  >
                    {{ data.label }}
                  </el-radio>
                  <!-- 父节点只显示文本 -->
                  <span v-else>{{ data.label }}</span>
                </span>
              </template>
            </el-tree>
          </div>
          <div class="no-knowledge" v-else>
            <p>暂无知识点,请前往课程章节-智能搭建中新增知识点</p>
          </div>
        </el-form-item>
        <el-form-item label="选择数字人：" prop="chooseShuziren">
          <el-select v-model="form.chooseShuziren" placeholder="请选择数字人">
            <el-option
              v-for="item in shuzirenList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="讲授内容：" prop="teachingContent">
          <el-input
            type="textarea"
            v-model="form.teachingContent"
            placeholder="输入的文字内容越丰富，生成视频所需的时间也会相应增加，请耐心等待。"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            color="#0070ff"
            class="generate-video-btn"
            @click="generateVideo"
            >生成视频</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <!-- 视频列表 -->
    <div class="video-list">
      <template v-if="videoUrl">
        <video
          class="video-content"
          :src="videoUrl"
          controls
          style="width: 768px; height: 768px"
        ></video>
      </template>
      <div class="video-loading" v-else-if="isLoading">
        <el-icon :size="40" color="#0070ff" class="loading-icon">
          <Loading />
        </el-icon>
        <span>视频生成中，当前页面不能关闭，请耐心等待...</span>
      </div>
      <div class="no-video" v-else>
        <p>暂无视频</p>
      </div>
    </div>

    <!-- 保存视频按钮 -->
    <div class="save-video-btn">
      <el-button type="primary" color="#0070ff" @click="saveVideo()"
        >保存视频并返回列表</el-button
      >
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      courseId: "",
      editId: "", // 视频id
      vid: "", // 视频id
      pid: "", // 形象数字人id
      kbId: "", // 知识点id
      form: {
        videoName: "",
        chooseShuziren: "",
        teachingContent: "",
      },
      rules: {
        videoName: [
          { required: true, message: "请输入视频名称", trigger: "blur" },
        ],
        chooseShuziren: [
          { required: true, message: "请选择数人", trigger: "blur" },
        ],
        teachingContent: [
          { required: true, message: "请输入教学内容", trigger: "blur" },
        ],
      },
      treeData: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      isLoading: false, // 改为false，初始不显示加载状态
      shuzirenList: [],
      videoList: [],
      pollingTimer: null, // 轮询定时器
      videoLoading: false, // 视频生成加载状态
      videoUrl: "",
      videoFileName: "",
      videoFileTime: "",
      selectedKnowledgeValue: "", // 选中的知识点value
    };
  },
  created() {
    this.editId = this.$route.query.id;
    this.courseId = JSON.parse(localStorage.getItem("courseId"));
    this.getKnowledgeList();
    this.getShuzirenList();
    this.getDetail();
    // this.getVideoList(); // 初始化时获取视频列表
  },
  methods: {
    // 获取视频列表
    getVideoList() {
      this.$axios
        .get(
          `/tes/course/auto/make/digital-human-list?courseId=${this.courseId}`
        )
        .then((res) => {
          this.videoList = res.data;
        });
    },

    // 获取知识点tree
    getKnowledgeList() {
      this.$axios
        .get(`/tes/course/auto/make/chapter-kb?courseId=${this.courseId}`)
        .then((res) => {
          this.treeData = res.data;
        });
    },

    // 获取数字人下拉
    getShuzirenList() {
      this.$axios.get(`/tes/digital-human/list?type=1&status=1`).then((res) => {
        this.shuzirenList = res.data;
      });
    },

    // 获取详情（编辑回显）
    getDetail() {
      if (!this.editId) return;
      this.$axios
        .get(`/tes/course/auto/make/digital-human-get?id=${this.editId}`)
        .then((res) => {
          this.form.videoName = res.data.name;
          this.form.chooseShuziren = res.data.digitalHumanId;
          this.form.teachingContent = res.data.description;
          this.selectedKnowledgeValue = res.data.kbId;
          this.videoUrl = res.data.filePath;
          this.videoFileName = res.data.fileName;
          this.videoFileTime = res.data.fileTime;
        });
    },

    // 处理知识点选择
    handleKnowledgeSelect(data) {
      this.kbId = data.value;
    },

    // 检查是否有可选择的知识点
    hasSelectableKnowledgePoints() {
      if (!this.treeData || this.treeData.length === 0) {
        return false;
      }

      // 递归检查树结构中是否有带value的节点（可选择的知识点）
      const checkNode = (nodes) => {
        for (let node of nodes) {
          if (node.value) {
            return true;
          }
          if (node.children && node.children.length > 0) {
            if (checkNode(node.children)) {
              return true;
            }
          }
        }
        return false;
      };

      return checkNode(this.treeData);
    },

    // 生成视频
    generateVideo() {
      if (this.isLoading) {
        this.$message.warning("视频生成中，请稍后再试");
        return;
      }
      if (!this.selectedKnowledgeValue) {
        this.$message.warning("请选择知识点");
        return;
      }
      if (this.videoUrl) {
        this.videoUrl = "";
        this.videoFileName = "";
        this.videoFileTime = "";
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          const data = {
            content: this.form.teachingContent,
            digtalHumanId: this.form.chooseShuziren,
          };
          this.videoLoading = this.$loading({
            lock: true,
            text: "加载中....",
            background: "rgba(0, 0, 0, 0.7)",
          });

          this.$axios
            .post(`/tes/digital-human/generate-video`, data)
            .then((res) => {
              this.vid = res.data.vId;
              this.pid = res.data.pId;
              this.videoLoading.close();
              // 开始轮询获取视频状态
              this.startPolling();
            })
            .catch((error) => {
              console.error("生成视频失败:", error);
              this.isLoading = false;
              this.videoLoading.close();
            });
        }
      });
    },

    // 开始轮询
    startPolling() {
      this.getVideoStatus();
    },

    // 停止轮询
    stopPolling() {
      if (this.pollingTimer) {
        clearTimeout(this.pollingTimer);
        this.pollingTimer = null;
      }
    },

    // 获取视频生成状态
    getVideoStatus() {
      this.$axios
        .post(`/tes/digital-human/get-video`, {
          vid: this.vid,
          pid: this.pid,
        })
        .then((res) => {
          console.log("视频状态:", res);
          const status = res.data.status;

          if (status === "wait") {
            this.isLoading = true;
            // 状态为wait，继续轮询，10秒后再次查询
            this.pollingTimer = setTimeout(() => {
              this.getVideoStatus();
            }, 10000);
          } else if (status === "success") {
            // 生成成功，停止轮询，获取视频列表
            this.videoUrl = res.data.url;
            this.videoFileName = res.data.fileName;
            this.videoFileTime = res.data.time;
            this.isLoading = false;
            this.stopPolling();
          } else {
            // 其他状态（如失败），停止轮询
            this.isLoading = false;
            this.stopPolling();
          }
        })
        .catch((error) => {
          console.error("获取视频状态失败:", error);
          this.isLoading = false;
          this.stopPolling();
        });
    },

    // 保存视频返回列表
    saveVideo() {
      if (this.isLoading) {
        this.$message.warning("视频生成中，请稍后再试");
        return;
      }
      if (!this.hasSelectableKnowledgePoints()) {
        this.$message.warning("暂无知识点,请前往课程章节-智能搭建中新增知识点");
        return;
      }
      if (!this.selectedKnowledgeValue) {
        this.$message.warning("请选择知识点");
        return;
      }
      if (!this.videoUrl) {
        this.$message.warning("请先生成视频");
        return;
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          let data = {};
          if (!this.editId) {
            data = {
              name: this.form.videoName,
              courseId: this.courseId,
              kbId: this.kbId,
              digitalHumanId: this.form.chooseShuziren,
              content: this.form.teachingContent,
              fileName: this.videoFileName,
              fileTime: this.videoFileTime,
            };
          } else {
            data = {
              id: this.editId,
              name: this.form.videoName,
              courseId: this.courseId,
              kbId: this.selectedKnowledgeValue,
              digitalHumanId: this.form.chooseShuziren,
              content: this.form.teachingContent,
              fileName: this.videoFileName,
              fileTime: this.videoFileTime,
            };
          }
          this.$axios
            .post(`/tes/course/auto/make/digital-human-save`, data)
            .then((res) => {
              this.$message.success("保存成功");
              this.$router.push({
                path: "/aiTeaching/courseBuild/shuzirenTeaching",
              });
            });
        }
      });
    },
  },

  // 组件销毁时清理定时器
  beforeDestroy() {
    this.stopPolling();
  },
};
</script>
<style lang="scss" scoped>
#add-shuziren-video {
  position: relative;
  background-color: #fff;
  padding: 40px 60px;
  box-sizing: border-box;
  .add-form {
    padding: 0 40px;
    display: flex;
    flex-direction: column;
    gap: 20px;
    .video-name {
      display: flex;
      align-items: center;
      span {
        flex-shrink: 0;
        font-size: 16px;
        color: #333;
        width: 100px;
      }
    }
    .knowledge-tree-item {
      position: relative;
      &::before {
        content: "*";
        position: absolute;
        left: 13px;
        top: 3px;
        color: #ff4949;
      }
    }
    .knowledge-tree {
      padding: 20px;
      border: 1px solid #ccc;
      max-height: 300px;
      width: 100%;
      overflow: auto;
      &::-webkit-scrollbar {
        width: 4px;
      }
      &::-webkit-scrollbar-track {
        background: transparent;
        border-radius: 5px;
      }
      &::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 5px;
        &:hover {
          background: #a8a8a8;
        }
      }
    }
    .no-knowledge {
      padding: 20px;
      border: 1px solid #ccc;
      max-height: 300px;
      width: 100%;
      p {
        font-size: 16px;
        color: #999;
      }
    }
    :deep(.el-textarea__inner) {
      height: 170px;
    }
  }
  .video-list {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 30px;
    width: 100%;
    padding-bottom: 33px;
    border-bottom: 1px solid #d8dbea;
    gap: 30px;
    .video-item {
      overflow: hidden;
      width: 100%;
      height: 471px;
      background: #ffffff;
      border-radius: 10px;
      border: 1px solid #b0b6cc;
    }
    .video-loading {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      gap: 20px;
      width: 100%;
      height: 471px;
      background: #ffffff;
      border-radius: 10px;
      border: 1px solid #b0b6cc;
      .loading-icon {
        animation: spin 1s linear infinite;
      }
      span {
        font-size: 16px;
        color: #000;
      }
    }
    .no-video {
      padding: 100px 0;
      p {
        font-size: 20px;
        color: #999;
      }
    }
  }

  .generate-video-btn {
    width: 150px;
    height: 42px;
  }

  .save-video-btn {
    display: flex;
    justify-content: center;
    align-items: center;
    .el-button {
      margin-top: 40px;
      width: 180px;
      height: 42px;
    }
  }
}
</style>


